package com.example.demo.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.example.demo.constant.SystemConstant;
import com.example.demo.controller.bean.Result;
import com.example.demo.dto.AdDTO;
import com.example.demo.mapper.entity.*;
import com.example.demo.dto.CheckAdDTO;
import com.example.demo.service.AdService;
import com.example.demo.utils.UserBasedCF;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Lucy
 * @create 2024-03-14 0:25
 */
@RequestMapping("ad")
@Api(value = "广告接口", tags = {"广告接口"})
@RestController
@Slf4j
public class AdController {

    @Autowired
    private AdService service;

    @Autowired
    private HttpServletRequest request;

    @ApiOperation("获取底部广告列表")
    @RequestMapping(value = "getAdList", method = {RequestMethod.POST})
    public Result<List<AdDTO>> getAdList(){
        List<UserAdClicks> allClicks = new ArrayList<>();
        List<AdClick> adClickList = service.selectAllAdClick();
        for(AdClick adClick : adClickList){
            Ad ad = service.selectAdById(adClick.getAdId());
            if(ad.getAdStatus() != 1) continue;
            UserAdClicks click = new UserAdClicks();
            click.setAdId(adClick.getAdId());
            click.setStudentId(adClick.getStudentId());
            Student student = service.selectStudentById(adClick.getStudentId());
            click.setCollegeId(student.getCollegeId());
            click.setGender(student.getGender());
            click.setNativePlace(student.getNativePlace());
            allClicks.add(click);
        }
        UserFeature targetUser = new UserFeature();
        int studentId = StpUtil.getLoginIdAsInt();
        Student student = service.selectStudentById(studentId);
        targetUser.setStudentId(studentId);
        targetUser.setGender(student.getGender());
        targetUser.setNativePlace(student.getNativePlace());
        targetUser.setCollegeId(student.getCollegeId());
        List<Recommendation> recommendations = UserBasedCF.recommendAds(allClicks, targetUser, 3);
        List<AdDTO> adDTOs = new ArrayList<>();
        for (Recommendation recommendation : recommendations) {
            Ad ad = service.selectAdById(recommendation.getAdId());
            AdDTO adDTO = new AdDTO();
            adDTO.setAdId(ad.getAdId());
            adDTO.setImageUrl(SystemConstant.aliyunOSSUrlPrefix + ad.getImageUrl());
            adDTO.setTitle(ad.getTitle());
            adDTO.setDetailUrl(SystemConstant.aliyunOSSUrlPrefix + ad.getDetailUrl());
            adDTOs.add(adDTO);
        }
        return Result.ok(adDTOs);
    }

    @ApiOperation("获取开屏广告")
    @RequestMapping(value = "getSplashAd", method = {RequestMethod.POST})
    public Result<Object> getSplashAd(){
        int studentId = StpUtil.getLoginIdAsInt();
        List<AdStudent> adStudentList = service.selectAdStudent(studentId);
        if(adStudentList.size() == 0) return Result.ok("暂无开屏广告");
        for(AdStudent adStudent : adStudentList){
            Ad ad = service.selectAdById(adStudent.getAdId());
            if(ad.getAdStatus() != 1) continue;
            AdSetting setting = service.selectSetting();
            List<AdKey> adKeyList = service.selectAllAdKey();
            AdKey currentAdKey = service.selectAdKeyById(adStudent.getAdId());
            int genderCount = 0;
            int nativePlaceCount = 0;
            int collegeCount = 0;
            for (AdKey adKey : adKeyList) {
                if(adKey.getGender() == currentAdKey.getGender()) genderCount++;
                if(adKey.getNativePlace() == currentAdKey.getNativePlace()) nativePlaceCount++;
                if(adKey.getCollegeId() == currentAdKey.getCollegeId()) collegeCount++;
            }
            int count = adKeyList.size();
            double clickCost = setting.getCostPerClick() + (genderCount + nativePlaceCount + collegeCount)/count*setting.getKeyRatio();
            AdTransaction transaction = new AdTransaction();
            transaction.setAdvertiserId(ad.getAdvertiserId());
            transaction.setAmount(clickCost);
            transaction.setTransactionType(3);
            service.insertAdTransaction(transaction);
            Advertiser advertiser = service.selectAdvertiserById(ad.getAdvertiserId());
            service.updateAderBalance(advertiser, clickCost);
            Map<String, Object> map = new HashMap<>();
            map.put("imageUrl", SystemConstant.aliyunOSSUrlPrefix + ad.getImageUrl());
            map.put("showTime",setting.getShowTime());
            return Result.ok(map);
        }
        return Result.ok("暂无开屏广告");
    }

    @ApiOperation("点击底部广告")
    @PostMapping( "/checkAd")
    public Result<String> checkAd(@RequestBody CheckAdDTO dto){
        int studentId = StpUtil.getLoginIdAsInt();
        Ad ad = service.selectAdById(dto.getAdId());
        AdSetting setting = service.selectSetting();
        AdClick adClick = new AdClick();
        adClick.setAdId(ad.getAdId());
        adClick.setStudentId(studentId);
        adClick.setClickCost(setting.getCostPerClick());
        adClick.setIPAddress(request.getRemoteAddr());
        adClick.setDeviceInfo(dto.getDeviceInfo());
        service.insertAdClick(adClick);
        AdTransaction transaction = new AdTransaction();
        transaction.setAdvertiserId(ad.getAdvertiserId());
        transaction.setAmount(setting.getCostPerClick());
        transaction.setTransactionType(2);
        service.insertAdTransaction(transaction);
        Advertiser advertiser = service.selectAdvertiserById(ad.getAdvertiserId());
        service.updateAderBalance(advertiser, setting.getCostPerClick());
        return Result.ok("点击成功");
    }
}
